﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace YJKRevitBase.ExcelUtility
{
	internal static class ExcelUtilityMethod
	{
		internal static void SetProperty(object obj, string propertyName, object[] values)
		{
			try
			{
				obj.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, obj, values);
			}
			catch (Exception ex)
			{
				PropertyInfo[] properties = obj.GetType().GetProperties();
				List<string> list = new List<string>();
				foreach (PropertyInfo propertyInfo in properties)
				{
					list.Add(propertyInfo.Name);
				}
				throw ex;
			}
		}

		internal static object GetProperty(object obj, string propertyName)
		{
			return obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, obj, null);
		}

		internal static object GetProperty(object obj, string propertyName, object[] values)
		{
			return obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, obj, values);
		}

		internal static object UseMethod(object obj, string MethodName, object[] values)
		{
			object result;
			try
			{
				result = obj.GetType().InvokeMember(MethodName, BindingFlags.InvokeMethod, null, obj, values);
			}
			catch (Exception)
			{
				object property = ExcelUtilityMethod.GetProperty(obj, "Application");
				try
				{
					ExcelUtilityMethod.SetProperty(property, "Visible", new object[]
					{
						true
					});
					object obj2 = obj.GetType().InvokeMember(MethodName, BindingFlags.InvokeMethod, null, obj, values);
					ExcelUtilityMethod.SetProperty(obj2, "Visible", new object[]
					{
						false
					});
					result = obj2;
				}
				catch (Exception ex)
				{
					throw ex;
				}
			}
			return result;
		}

		public static int TitleToNumber(string s)
		{
			string text = s.ToUpper();
			int num = 0;
			int length = s.Length;
			char c = 'A';
			for (int i = 0; i < length; i++)
			{
				int num2 = (int)(text[i] - c + '\u0001');
                num2 *= (int)System.Math.Pow(26.0, (double)(length - i - 1));
				num += num2;
			}
			return num;
		}

		public static string ConvertToTitle(int n)
		{
			List<int> list = new List<int>();
			int i;
			for (i = n; i > 26; i /= 26)
			{
				if (i % 26 == 0)
				{
					list.Add(26);
					i -= 26;
				}
				else
				{
					list.Add(i % 26);
					i -= i % 26;
				}
			}
			list.Add(i);
			list.Reverse();
			StringBuilder stringBuilder = new StringBuilder();
			foreach (int num in list)
			{
				stringBuilder.Append((char)(num - 1 + 65));
			}
			return stringBuilder.ToString();
		}
	}
}
